package com.hp.idempotence.v1.config;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.hp.idempotence.v1.annotation.IdempotentAno;

@Component
public class MyHandle implements HandlerInterceptor {
	
	private static Logger logger = LoggerFactory.getLogger(MyHandle.class);
	
	private final static int MAX_MINS = 1;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		if(handler instanceof HandlerMethod){
			
			IdempotentAno idempotentAno = ((HandlerMethod) handler).getMethodAnnotation(IdempotentAno.class);
			
			if(idempotentAno != null ){
				
				//使用同步锁 判断接口调用时间 如果是很短小于 MAX_MINS 时间提交 返回异常提示
				vaiRepSubmit(request);
				
			}
		}
		
		return HandlerInterceptor.super.preHandle(request, response, handler);
	}
	
	
	
	/**
	 * 用 url+param 作为key 请求时间作为value
	 * 计算相同请求的时间差 如果时间差在重复提交的间隔内 抛出异常
	 * @param request
	 * @throws Exception
	 */
	
	public void vaiRepSubmit(HttpServletRequest request) throws Exception{
		
		HttpSession session = request.getSession();
		String url = request.getRequestURI();
		String param = request.getParameterMap().toString();
		
		String http_param = String.format("%s:%s", url, param);
		
		Date new_date = new Date();
		
		logger.info("新的请求参数{}",String.format("%s,时间 %tF %tT", http_param, new_date, new_date));
		
		synchronized (session) {
			
			if(session != null){
				
				Date old_param = (Date)session.getAttribute(http_param);
				
				if(old_param!=null && (new_date.getTime()-old_param.getTime()) <= MAX_MINS*1000){
					
					logger.info("老的的请求参数{}",String.format("%s,时间 %tF %tT", http_param, new_date, new_date));
					
					throw new InterruptedException("表单重复提交!");
				
				}
			}
			
			session.setAttribute(http_param, new_date);
			
		}
	}

}
